"""
@-*- coding: utf-8 -*-
@ python: 3.12.3
@ 创建者: JacksonCode
@ 创建时间: 2025-11-06
@ 描述: 用户控制器，处理用户管理相关的业务逻辑
"""
from flask import request
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.common.base_controller import BaseController
from app.services.users import UserService
from app.utils.decorators import admin_required


class UserController(BaseController):
    """用户控制器，处理用户管理相关的业务逻辑"""
    
    @staticmethod
    @jwt_required()
    def get_users():
        """获取用户列表（分页）"""
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        
        # 限制每页最大数量
        per_page = min(per_page, 100)
        
        pagination = UserService.get_all_users(page=page, per_page=per_page)
        
        users = []
        for user in pagination.items:
            users.append({
                "id": user.id,
                "email": user.email,
                "username": user.username,
                "is_admin": user.is_admin,
                "is_active": user.is_active,
                "created_at": user.created_at.isoformat() if hasattr(user, 'created_at') else None
            })
        
        pagination_data = {
            "page": page,
            "per_page": per_page,
            "total": pagination.total,
            "pages": pagination.pages,
            "has_next": pagination.has_next,
            "has_prev": pagination.has_prev
        }
        
        return UserController.success_response(
            "获取用户列表成功", 
            {"users": users, "pagination": pagination_data}
        )
    
    @staticmethod
    @jwt_required()
    def get_user(user_id):
        """获取指定用户信息"""
        user = UserService.get_user_by_id(user_id)
        
        if not user:
            return UserController.not_found_response("用户")
        
        user_data = {
            "id": user.id,
            "email": user.email,
            "username": user.username,
            "is_admin": user.is_admin,
            "is_active": user.is_active,
            "created_at": user.created_at.isoformat() if hasattr(user, 'created_at') else None
        }
        
        return UserController.success_response("获取用户信息成功", {"user": user_data})
    
    @staticmethod
    @admin_required
    def delete_user(user_id):
        """删除用户（仅管理员）"""
        current_user_id = get_jwt_identity()
        
        # 不允许删除自己
        if current_user_id == user_id:
            return UserController.error_response("不能删除自己的账户", 400)
        
        success = UserService.delete_user(user_id)
        
        if not success:
            return UserController.not_found_response("用户")
        
        return UserController.success_response("用户删除成功")
    
    @staticmethod
    @admin_required
    def activate_user(user_id):
        """激活用户（仅管理员）"""
        user = UserService.get_user_by_id(user_id)
        
        if not user:
            return UserController.not_found_response("用户")
        
        user.is_active = True
        from app.extensions import db
        db.session.commit()
        
        user_data = {
            "id": user.id,
            "email": user.email,
            "username": user.username,
            "is_active": user.is_active
        }
        
        return UserController.success_response("用户激活成功", {"user": user_data})
    
    @staticmethod
    @admin_required
    def deactivate_user(user_id):
        """停用用户（仅管理员）"""
        user = UserService.get_user_by_id(user_id)
        
        if not user:
            return UserController.not_found_response("用户")
        
        current_user_id = get_jwt_identity()
        
        # 不允许停用自己
        if current_user_id == user_id:
            return UserController.error_response("不能停用自己的账户", 400)
        
        user.is_active = False
        from app.extensions import db
        db.session.commit()
        
        user_data = {
            "id": user.id,
            "email": user.email,
            "username": user.username,
            "is_active": user.is_active
        }
        
        return UserController.success_response("用户停用成功", {"user": user_data})